//
//  SetSafeAreaViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/20.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "SetSafeAreaViewController.h"
#import "SelectPositionViewController.h"
#import "SafeAreaListViewController.h"
#import "DataManager.h"
#import "SyncManager.h"
#import "AppDelegate.h"
#import "SGLocation.h"
@interface SetSafeAreaViewController ()
{
    SingleRangeSlider *slider;
    UIButton *_locationButton;
    CLLocationCoordinate2D centerCoordinate;
    float radius;
}
@property (nonatomic, strong) NSMutableArray *overlaysAboveRoads;
@property (nonatomic,strong) MACircle *circle;
@property (nonatomic, strong) NSMutableArray *annotations;
@property(nonatomic,retain) Location *location;
@property(nonatomic,retain) Watch *selectWatch;
@property (nonatomic,retain) DataManager *dataManager;
@property (nonatomic,retain) SyncManager *syncManager;
@property(nonatomic,retain) User *user;
@end

@implementation SetSafeAreaViewController
@synthesize sliderBarView;
@synthesize setInfoView;
//@synthesize navLeftButton;
//@synthesize navRightButton;
@synthesize nameLabel;
@synthesize overlaysAboveRoads = _overlaysAboveRoads;
@synthesize circle = _circle;
@synthesize positionLabel;
@synthesize chooseImage;
@synthesize nowRangeLabel;
//@synthesize fenceIDString;
@synthesize nameMap;

bool isHaveWatchPosition;
bool isHavePhonePosition;
bool isNotiHaveSent;
bool isAnnotationHaveAdd;
- (void)viewDidLoad {
    nameMap = [NSArray arrayWithObjects:@"学校",@"家",@"其他",nil];
    //self.chooseImage.image=[UIImage imageWithCGImage:[UIImage imageNamed:@"next.png"].CGImage scale:1 orientation:UIImageOrientationRight];
    self.nameLabel.delegate=self;
    [self clearMapView];
    [super viewDidLoad];
    [self registerObservers];
    [self initNavButton];
    [self initLocalProxy];
    [self getWatchPosition];
    

    
    
    //[self initSliderBar];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [self initSubMapView];
    [self initControls];
    [self initActions];
    [self initSliderBar];
    [self.view addSubview:sliderBarView];
    [self.view bringSubviewToFront:sliderBarView];
    [self setValueIfExist];
    [self initOverlays:NO];
    //有放大缩小的滑动框，避免手势冲突将系统滑动返回关闭
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self clearMapView];
    //有放大缩小的滑动框，避免手势冲突将系统滑动返回关闭
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

}

-(void)initLocalProxy
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    self.dataManager = [[DataManager alloc] init];
    self.syncManager = [[SyncManager alloc]init];
    self.user=[User sharedSingleton];
    self.mapView = myDelegate.mapView;
    self.search = myDelegate.search;
}

-(void)setValueIfExist
{
    if (self.fence != NULL) {
        if (self.fence.type==100){self.nameLabel.text=self.fence.title;}
        else{
            self.nameLabel.text = [self getNameWithType:self.fence.type];}
        self.positionLabel.text = self.fence.desc?:@"";
        centerCoordinate = CLLocationCoordinate2DMake(self.fence.latitude,self.fence.longtitude);
        self.location.latitude = self.fence.latitude;
        self.location.longtitude = self.fence.longtitude;
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(self.fence.latitude, self.fence.longtitude) animated:YES];
        radius = self.fence.radius;
        nowRangeLabel.text=[NSString stringWithFormat:@"%.0fm",self.fence.radius];
        //sliderBar.value = radius;
        slider.selectedMaximumValue = radius;
    }
}
#pragma mark - Life Cycle

//- (id)init
//{
//    self = [super init];
//    if (self)
//    {
//        [self initOverlays];
//    }
//    
//    return self;
//}

#pragma mark - Initialization

- (void)initOverlays:(BOOL)isNeedInit
{
    if(isHaveWatchPosition||isNeedInit){
        self.overlaysAboveRoads = [NSMutableArray array];
        /* Circle. */
        //self.circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(self.location.latitude, self.location.longtitude) radius:300];
        self.circle = [MACircle circleWithCenterCoordinate:centerCoordinate radius:(radius?:300)];
        [self.overlaysAboveRoads addObject:self.circle];
    
        MAPointAnnotation *centerAnnotation = [[MAPointAnnotation alloc] init];
        //    centerAnnotation.coordinate = CLLocationCoordinate2DMake(self.location.latitude, self.location.longtitude);
        centerAnnotation.coordinate = centerCoordinate;
        centerAnnotation.title = @"location_now";
        NSLog(@"addAnnotation=============");
        [self.mapView addAnnotation:centerAnnotation];
        [self.mapView addOverlays:self.overlaysAboveRoads level:MAOverlayLevelAboveRoads];
    }
}

- (void)initOverlaysWithDefaulPosition{
    isAnnotationHaveAdd = NO;
    if (isHavePhonePosition) {
        SGLocation *loc = [SGLocation shareLocation];;
        [loc setGetCity:^(NSString *city) {
            self.positionLabel.text = city;
        }];
        [loc setGetLocation:^(NSString *location) {
            self.positionLabel.text = [self.positionLabel.text stringByAppendingString:location];
        }];
        [loc setGetCoordinate:^(CLLocationCoordinate2D coodinate) {
            NSLog(@"%f-%f",coodinate.latitude,coodinate.longitude);
            if (!isAnnotationHaveAdd) {
                isAnnotationHaveAdd = YES;
                self.location.latitude = coodinate.latitude;
                self.location.longtitude = coodinate.longitude;
                centerCoordinate = CLLocationCoordinate2DMake(coodinate.latitude, coodinate.longitude);
                [self initOverlays:YES];
                [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(coodinate.latitude, coodinate.longitude) animated:YES];
            }
        }];
    }else{
        [self initOverlays:YES];
    }
}

-(void)initActions{
    //disable TextField edit
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    if(myDelegate!=NULL&&myDelegate.isAdmin==NO)
    {
        self.nameLabel.enabled=NO;
        self.positionLabel.enabled=NO;
    }
    else
    {
        UITapGestureRecognizer *tapReconizerToGrade = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setPositionAction)];
        UIView *chooseImageContainerView=[[UIView alloc]initWithFrame:CGRectMake(self.chooseImage.frame.origin.x-self.chooseImage.frame.size.width*0.5, self.chooseImage.frame.origin.y-self.chooseImage.frame.size.height*0.5, self.chooseImage.frame.size.width*2, self.chooseImage.frame.size.height*2)];
        chooseImageContainerView.backgroundColor=[UIColor clearColor];
        [self.setNameView addSubview:chooseImageContainerView];
        [chooseImageContainerView addGestureRecognizer:tapReconizerToGrade];
    }


}

-(void)setPositionAction
{
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    SelectPositionViewController *selectPosition=[[SelectPositionViewController alloc]init];
    [selectPosition setMotherWindow:alertView];
    [selectPosition setMotherLabel:nameLabel];
    
    alertView.rootViewController=selectPosition;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

- (void)initNavButton {
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"设置安全区域";
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL&&mydelegate.isAdmin==YES)
    {
        UIBarButtonItem *navRightButton=[[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
        //[navRightButton setTarget:self];
        //[navRightButton setAction:@selector(saveAction)];
        self.navigationItem.rightBarButtonItem=navRightButton;
    }

}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    [self clearMapView];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getWatchPosition{
    isHaveWatchPosition=YES;
    isHavePhonePosition=NO;
    isNotiHaveSent = NO;
    //如果已有地址则为修改安全区域，所以不做改动直接退出
//    if ((self.orignalLocation!=nil)&&(![self.orignalLocation isEqual:@""])&&(![self.orignalLocation isEqual:@"(null)"])){
//        return;
//    }
    __block NSString *testLocation=[[NSString alloc]init];
    testLocation=@"";
    self.selectWatch=[self.dataManager getActiveWatch:self.user.uid];
    self.location = [self.dataManager getLatestLocation:self.selectWatch.deviceUid];
    if (self.fence != nil) {
        return;
    }
    centerCoordinate = CLLocationCoordinate2DMake(self.location.latitude,self.location.longtitude);
    self.positionLabel.text = self.location.mainAddress;
    if ((positionLabel.text==nil)||([positionLabel.text isEqual:@""])||([positionLabel.text isEqual:@"(null)"])){
        //手表无位置，转移为手机位置
        isHaveWatchPosition=NO;
        SGLocation *loc = [SGLocation shareLocation];
        [loc setGetCity:^(NSString *city) {
            testLocation = city;
        }];
        [loc setGetLocation:^(NSString *location) {
            testLocation = [testLocation stringByAppendingString:location];
            //手机无位置，转移为天安门位置
            if ((testLocation==nil)||([testLocation isEqual:@""])||([testLocation isEqual:@"(null)"])){
                isHavePhonePosition=NO;
                positionLabel.text=@"北京天安门";
                self.location.latitude = 39.90960456049752;
                self.location.longtitude = 116.3972282409668;
                centerCoordinate = CLLocationCoordinate2DMake(39.90960456049752, 116.3972282409668);
                [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.90960456049752, 116.3972282409668) animated:YES];
            }else{
                isHavePhonePosition=YES;
            }
            if (!isNotiHaveSent) {
                isNotiHaveSent = YES;
                NSLog(@"===================send=====================");
                [[NSNotificationCenter defaultCenter] postNotificationName:HAVEALREADYGETPHONEPOSITION object:nil  userInfo:nil];
            }
        }];
    //positionLabel.text=@"";
    }else{
        positionLabel.enabled=NO;
        if ((self.location.subAddress!=nil)&&(![self.location.subAddress isEqual:@""])&&(![self.location.subAddress isEqual:@"(null)"])){
        self.positionLabel.text = [self.location.mainAddress stringByAppendingString:self.location.subAddress];
        }

    }

}

-(void)saveAction{
    self.navigationItem.rightBarButtonItem=nil;
    NSLog(@"%@",nameLabel.text);
    if ((nameLabel.text==nil)||([nameLabel.text isEqual:@""]))
    {
        [LeoMsg showMsg:@"请添加名称"];
        [self initNavButton];
        NSLog(@"%@",nameLabel.text);
        return;
    }
    if ([LeoMsg isTooLong:nameLabel.text ChnLength:40 EngLength:20 tipsString:@"安全区域名称" onlyUnderline:NO])
    {
        [self initNavButton];
        return;
    }
    Fence *fence = [[Fence alloc]init];
    fence.deviceUid = self.selectWatch.deviceUid;
    fence.latitude = self.location.latitude;
    fence.longtitude = self.location.longtitude;
    fence.radius = slider.selectedMaximumValue;
    fence.is_active = 1;
    fence.cycle = @"1,2,3,4,5,6,7";
    fence.type = [self getNameType:self.nameLabel.text];
    fence.title=nameLabel.text;
    fence.desc = self.positionLabel.text;
    if(self.dataManager==NULL)
    {
        [self initNavButton];
        return;
    }

    if (self.fence != NULL) {
        fence.fence_id = self.fence.fence_id;
        if([self.dataManager IsSameFence:fence isNew:NO]==YES)
        {
            [LeoMsg showMsg:@"已存在完全相同的安全区域，请重新选择中心点或者半径"];
            [self initNavButton];
            return;
        }
        [self.syncManager setGeoFence:self.selectWatch.deviceUid fence:fence completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if (result==SUCESS)
            {
                [self.navigationController popViewControllerAnimated:YES];
                [self clearMapView];
            }
            else
            {

                [Tooler showHttpMsg:result description:description msg:@"设置安全区域失败"];
                [self initNavButton];
            }
        }];
        return;
    }
    if([self.dataManager IsSameFence:fence isNew:YES]==YES)
    {
        [LeoMsg showMsg:@"已存在完全相同的安全区域，请重新选择中心点或者半径"];
        [self initNavButton];
        return;
    }
    [self.syncManager addGeoFence:self.selectWatch.deviceUid fence:fence completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if (result==SUCESS)
        {
            [self.navigationController popViewControllerAnimated:YES];
            [self clearMapView];
        }
        else
        {

            [Tooler showHttpMsg:result description:description msg:@"添加安全区域失败"];
            [self initNavButton];
        }

    }];
//    [self.navigationController popViewControllerAnimated:YES];
//    [self clearMapView];
}

- (void)initSliderBar{
    CGRect rect = [UIScreen mainScreen].bounds;
    NSLog(@"%f",rect.size.height);
    slider =  [[SingleRangeSlider alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, 44)];
    slider.maximumValue = 500;
    slider.selectedMaximumValue = 300;
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    if(myDelegate!=NULL&&myDelegate.isAdmin==NO)
    {
        slider.enabled=NO;
    }
    else
    {
       [slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    }
    [sliderBarView addSubview:slider];
}

-(void)initSubMapView{
    CGRect rect = [UIScreen mainScreen].bounds;
    self.mapView.frame = CGRectMake(0, 20+44+CGRectGetHeight(self.setInfoView.bounds), CGRectGetWidth(self.view.bounds), rect.size.height-(20+44+CGRectGetHeight(self.setInfoView.bounds)));
    self.mapView.showsCompass = NO;
    [self.mapView setZoomLevel:15 animated:YES];
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(self.location.latitude, self.location.longtitude)animated:YES];
}

- (void) sliderValueChanged:(id)sender{
    nowRangeLabel.text=[NSString stringWithFormat:@"%.0fm",slider.selectedMaximumValue];
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.overlaysAboveRoads removeAllObjects];
    //[self.mapView removeAnnotations:self.mapView.annotations];
//    self.circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(self.location.latitude, self.location.longtitude) radius:sliderBar.value];
    //self.circle = [MACircle circleWithCenterCoordinate:centerCoordinate radius:sliderBar.value];
    self.circle = [MACircle circleWithCenterCoordinate:centerCoordinate radius:slider.selectedMaximumValue];
    [self.overlaysAboveRoads addObject:self.circle];
    [self.mapView addOverlays:self.overlaysAboveRoads level:MAOverlayLevelAboveRoads];
    
}
// add button to active location service
-(void)initControls{
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NSLog(@"%f",CGRectGetWidth(self.mapView.bounds));
    _locationButton.frame = CGRectMake(CGRectGetWidth(self.mapView.bounds)-40, 10, 40, 40);
    _locationButton.autoresizingMask =
        UIViewAutoresizingFlexibleLeftMargin |
        UIViewAutoresizingFlexibleBottomMargin;
    _locationButton.backgroundColor = [UIColor whiteColor];
    _locationButton.layer.cornerRadius = 5;

    [_locationButton addTarget:self action:@selector(locationAction) forControlEvents:UIControlEventTouchUpInside];
    [_locationButton setImage:[UIImage imageNamed:@"location_now"] forState:UIControlStateNormal];
    [self.mapView addSubview:_locationButton];
}

-(void)locationAction{
    if (self.mapView.userTrackingMode != MAUserTrackingModeFollow) {
        [self.mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES];
    }
}

- (void)clearMapView
{
    self.mapView.showsUserLocation = NO;
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    //[self.mapView setMapStatus: self.lastStatus animated:NO duration:0];
    self.mapView.delegate = nil;
    [self.mapView setCompassImage:nil];
    [_locationButton removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)mapView:(MAMapView *)mapView didLongPressedAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    [self searchReGeocodeWithCoordinate:coordinate];
}

- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location                    = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension            = YES;
    
    [self.search AMapReGoecodeSearch:regeo];
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(request.location.latitude, request.location.longitude);
        [self.mapView removeAnnotations:self.mapView.annotations];
        [self.mapView removeOverlays:self.mapView.overlays];
        self.overlaysAboveRoads = [NSMutableArray array];
        self.circle = [MACircle circleWithCenterCoordinate:coordinate radius:(radius?:300)];
        [self.overlaysAboveRoads addObject:self.circle];
        
        MAPointAnnotation *centerAnnotation = [[MAPointAnnotation alloc] init];
        //    centerAnnotation.coordinate = CLLocationCoordinate2DMake(self.location.latitude, self.location.longtitude);
        centerAnnotation.coordinate = coordinate;
        centerCoordinate = coordinate;
        centerAnnotation.title = @"location_now";
        [self.mapView addAnnotation:centerAnnotation];
        [self.mapView setCenterCoordinate:coordinate animated:YES];
        [self.mapView addOverlays:self.overlaysAboveRoads level:MAOverlayLevelAboveRoads];
        self.positionLabel.text = response.regeocode.formattedAddress;
        self.location.latitude = request.location.latitude;
        self.location.longtitude = request.location.longitude;
        
    }
    else /* from drag search, update address */
    {
        
    }
}

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    if(updatingLocation)
    {
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAAnnotationView *annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:pointReuseIndetifier];
        }
        
        annotationView.canShowCallout               = YES;
        annotationView.draggable                    = YES;
        annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        annotationView.image                        = [UIImage imageNamed:@"security_point"];
        annotationView.centerOffset                 = CGPointMake(0, 0);
        return annotationView;
    }
    
    return nil;
}

-(MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MACircle class]])
    {
        MACircleView *circleView = [[MACircleView alloc] initWithCircle:overlay];
        
        circleView.lineWidth    = 2.f;
        circleView.strokeColor  = [UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0];
        circleView.fillColor    = [UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:0.2];
        circleView.lineDash     = NO;
        
        return circleView;
    }
    return nil;
}

- (int)getNameType:(NSString *)name{
    /*
    switch ([nameMap indexOfObject:name]) {
        case 0:
            return 0;
            break;
        case 1:
            return 1;
            break;
        default:
            return 2;
            break;
    }*/
    if(name!=NULL&&[name isEqualToString:@"学校"])
        return 1;
    else if(name!=NULL&&[name isEqualToString:@"家"])
        return 2;
    else
        return 100;
}

- (NSString*)getNameWithType:(int)type
{
    NSString *name=@"其他";
    switch (type) {
        case 1:
            name=@"学校";
            break;
        case 2:
            name=@"家";
            break;
        case 3:
        case 100:
        {
            if(self.fence!=NULL&&self.fence.title!=NULL&&![self.fence.title isEqualToString:@"(null)"]&&![self.fence.title isEqualToString:@""])
                name=self.fence.title;
            break;
        }
    }
    return name;
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [nameLabel resignFirstResponder];
    [positionLabel resignFirstResponder];
}

- (void)registerObservers{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(initOverlaysWithDefaulPosition) name:HAVEALREADYGETPHONEPOSITION object:nil];
}

- (void)removeObservers{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:HAVEALREADYGETPHONEPOSITION object:nil];
}

@end
